package com.oto.util;

import java.io.Reader;
import java.io.Writer;
import java.util.List;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.PropertyException;
import javax.xml.bind.Unmarshaller;

import com.oto.model.FlowDO;
import com.oto.web.model.Message;
import com.oto.web.model.ObjectFactory;
import com.oto.web.model.XmlFlow;
import com.oto.web.model.XmlPack;

/**
 * JAXB工具类
 * 
 * @author xueqiang.mi
 * @since 2010-12-05
 */
public class JAXBUtils {

	/**
	 * Generate JAXBElement object through a list of XMLPackage object
	 */
	public static Message generateLivingFlow(List<XmlPack> packs) {
		ObjectFactory objectFactory = new ObjectFactory();
		Message livingFlow = objectFactory.createMessage();
		livingFlow.setPacks(packs);
		return livingFlow;
	}

	/**
	 * Generate JAXBElement object through a list of Flow object
	 */
	public static XmlPack generateXMLPackage(List<FlowDO> flowList) {
		ObjectFactory factory = new ObjectFactory();
		XmlPack xPack = factory.createPack();
		xPack.setId(0L);
		xPack.setName("");
		xPack.setType("");
		for (FlowDO f : flowList) {
			XmlFlow xFlow = factory.createFlow();
			xFlow.setId(f.getId());
			xFlow.setName(f.getName());
			xFlow.setContent(f.getContent());
			String[] types = f.getType().split("-");
			xFlow.setType(types[0]);

			xPack.getFlows().add(xFlow);
		}
		return xPack;
	}

	/**
	 * Marshal Operation
	 * 
	 * @param contextPath
	 * @param je
	 * @param writer
	 */
	public static void marshal(String contextPath, JAXBElement<?> je, Writer writer) {
		try {
			JAXBContext jc = JAXBContext.newInstance(contextPath);
			Marshaller marshaller = jc.createMarshaller();
			marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
			marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

			marshaller.marshal(je, writer);
		} catch (PropertyException e) {
			e.printStackTrace();
		} catch (JAXBException e) {
			e.printStackTrace();
		}
	}

	/**
	 * UnMarshal Operation
	 * 
	 * @param <T>
	 * @param contextPath
	 * @param reader
	 */
	@SuppressWarnings("unchecked")
	public static <T> T unmarshal(String contextPath, Reader reader) {
		try {
			JAXBContext jc = JAXBContext.newInstance(contextPath);
			Unmarshaller unmarshaller = jc.createUnmarshaller();

			JAXBElement<T> je = (JAXBElement<T>) unmarshaller.unmarshal(reader);
			return je.getValue();
		} catch (JAXBException e) {
			e.printStackTrace();
		}
		return null;
	}
}
